#include "tcp.h"

#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

static tcp_sess_t *session_create(tcp_t *srv, int sock);
static void session_delete(tcp_t *srv, tcp_sess_t *s);

static int client_init(tcp_t *cli)
{
    int ret = 0;

    /* get socket */
    cli->sock = socket(AF_INET, SOCK_STREAM, 0);
    if (cli->sock < 0) {
        printf("socket: failed!\n");
        return -1;
    }

    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = inet_addr(cli->addr),
        .sin_port = htons(cli->port),
    };

    socklen_t len = sizeof(struct sockaddr_in);

    /* connect socket */
    ret = connect(cli->sock, (const struct sockaddr *)&addr, len);
    if (ret < 0) {
        printf("connect: failed!\n");
        return -1;
    }

    return 0;
}

static int server_init(tcp_t *srv)
{
    int ret = 0;

    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = htonl(INADDR_ANY),
        .sin_port = htons(srv->port),
    };

    /* get socket */
    srv->sock = socket(AF_INET, SOCK_STREAM, 0);
    if (srv->sock < 0) {
        printf("socket: failed!\n");
        return -1;
    }

    /* reuse socket addr */
    int opt = SO_REUSEADDR;
    setsockopt(srv->sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    /* bind socket */
    ret = bind(srv->sock, (struct sockaddr *)&addr, sizeof(addr));
    if (ret < 0) {
        printf("bind: failed!\n");
        close(srv->sock);
        return ret;
    }

    /* if port is 0, get real port */
    if (srv->port == 0) {
        socklen_t addrsize = sizeof(addr);
        getsockname(srv->sock, (struct sockaddr *)&addr, &addrsize);
        srv->port = ntohs(addr.sin_port);
    }

    /* listen socket */
    ret = listen(srv->sock, TCP_BACKLOG);
    if (ret < 0) {
        printf("listen: failed!\n");
        close(srv->sock);
        return ret;
    }

    return ret;
}

static int server_epoll(tcp_t *srv)
{
    int epfd;
    struct epoll_event event[TCP_SESSION_MAX];

    /* add server to epoll */
    epfd = epoll_create(1);
    srv->epfd = epfd;

    struct epoll_event ev = {
        .events = EPOLLIN,
        .data.ptr = srv,
    };

    if (epoll_ctl(epfd, EPOLL_CTL_ADD, srv->sock, &ev) < 0) {
        printf("epoll add: failed!\n");
        return -1;
    }

    /* temp pointer for client */
    tcp_sess_t *sess = NULL;
    list_init(&srv->head);

    for (;;) {
        /* epoll wait */
        int nepoll = epoll_wait(epfd, event, TCP_SESSION_MAX, -1);
        if (nepoll < 0) {
            printf("epoll wait error!\n");
            return -1;
        }

        for (int i = 0; i < nepoll; i++) {
            if (event[i].data.ptr == srv) { /* is server sock wake up, a new client connected. */
                /* get client sock */
                struct sockaddr_in addr;
                socklen_t len = sizeof(addr);

                int sock = accept(srv->sock, (struct sockaddr *)&addr, &len);
                if (sock < 0) {
                    printf("accept: failed!\n");
                    return -1;
                }

                /* create a new session, will add it to epoll and server list. */
                sess = session_create(srv, sock);
                // inet_ntop(AF_INET, &addr.sin_addr.s_addr, cli->ip, sizeof(cli->ip));
                // cli->port = ntohs(addr.sin_port);
                srv->on_open(sess);
            } else { /* is client socket wake up, client data is comming. */
                sess = event[i].data.ptr;
                if (srv->on_recv(sess) < 0) {
                    srv->on_exit(sess);
                    close(sess->sock);
                    /* delete sess, will del it from epoll and server list. */
                    session_delete(srv, sess);
                    event[i].data.ptr = NULL;
                }
            }
        }
    }  // end inf loop
}

// sock: session socket fd
// epfd: epoll fd
static tcp_sess_t *session_create(tcp_t *srv, int sock)
{
    /* create client object */
    tcp_sess_t *s = (tcp_sess_t *)malloc(sizeof(tcp_sess_t));
    if (s == NULL) {
        printf("malloc failed!\n");
        return NULL;
    }
    memset(s, 0, sizeof(tcp_sess_t));

    s->sock = sock;
    list_insert(&srv->head, &s->node);

    /* add client to epoll */
    struct epoll_event ev = {
        .events = EPOLLIN,
        .data.ptr = s,
    };

    if (epoll_ctl(srv->epfd, EPOLL_CTL_ADD, sock, &ev) < 0) {
        printf("epoll add: failed!\n");
        return NULL;
    }

    return s;
}

static void session_delete(tcp_t *srv, tcp_sess_t *s)
{
    epoll_ctl(srv->epfd, EPOLL_CTL_DEL, s->sock, NULL);
    list_remove(&s->node);
    free(s);
    s = NULL;
}

int tcp_new_srv(tcp_t *srv)
{
    int ret = 0;

    ret = server_init(srv);
    if (ret < 0) {
        return ret;
    }

    if (srv->on_sock != NULL) {
        srv->on_sock((void *)srv);
    }

    return server_epoll(srv);
}

int tcp_new_cli(tcp_t *cli)
{
    return client_init(cli);
}

int sendbuf(int sock, void *buf, int len)
{
    return send(sock, buf, len, 0);
}

int recvbuf(int sock, void *buf, int len)
{
    return recv(sock, buf, len, 0);
}

int sendall(int sock, void *buf, int len)
{
    int ret = 0;
    int off = 0;

redo:
    ret = send(sock, buf + off, len - off, 0);
    if (ret <= 0) {
        return ret;
    }
    off += ret;
    if (off < len) {
        goto redo;
    }

    return off;
}

int recvall(int sock, void *buf, int len)
{
    int ret = 0;
    int off = 0;

redo:
    ret = recv(sock, buf + off, len - off, 0);
    if (ret <= 0) {
        return ret;
    }
    off += ret;
    if (off < len) {
        goto redo;
    }

    return off;
}
